import fetch from 'isomorphic-fetch';
import AuthManager from './auth'
const errorMessages = (res) => `${res.status} ${res.statusText}`;
const baseApiUrl = 'http://10.129.115.29';

function check401(res) {
  if (res.status == 401) {
    throw new Error("需要重新登录");
  }
  return res;
}

function check404(res) {
  if (res.status == 404) {
    throw new Error("需要重新登录");
  }
  return res;
}

function jsonParse(res) {
  return res.json().then((jsonResult) => ({...jsonResult}));
}

function errorMessagesParser(jsonResult) {
  const { success, message, data } = jsonResult;
  if (!success) {
    throw new Error(message);
  }
  return jsonResult;
}

function xFetch(url, input) {
  let urlC = AuthManager.loggedIn() ? baseApiUrl+url+'?token='+AuthManager.getToken() : baseApiUrl+url;
  return fetch(urlC,
  {
    method:'POST',
    cache: 'default',
    body:JSON.stringify(input)
  }
).then(check401)
    .then(check404)
    .then(jsonParse)
  .then(errorMessagesParser);
}

export default xFetch;
